<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Article;
use App\Constants\TagConstant;
use App\Models\ArticleComment;
use App\Models\Publisher;
use App\Models\Tag;
use App\Services\MiniProgramService;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Show;
use Dcat\Admin\Widgets\Tab;
use Illuminate\Http\Request;

class HotArticleController extends AdminController
{
    public function index(Content $content)
    {
        $tab = Tab::make();
        $tab->add('热点快讯', $this->grid(), true);
        $tab->addLink('标签', admin_route('hot_news_tags.index'));
        $tab->addLink('草稿箱', admin_route('hot_articles_draft.index'));
        return $content->body($tab->withCard());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Article(['hot_news_tag']), function (Grid $grid) {
            $map = getAuthMiniProgramMap(Admin::user()->id);
            $grid->model()->whereIn('mini_type', array_keys($map));

            $grid->model()->where('type', '=', 1);
            $grid->model()->orderByDesc('created_at');
            $grid->column('created_at');
            $grid->column('mini_type')->display(function ($miniType) use ($map) {
                return $miniType ? $map[$miniType] : '';
            });
            $grid->column('id');
            $grid->column('mini_app_short_link', '小程序短链')->display('查看')->modal(function ($modal) {
                $modal->title('小程序短链');
                $modal->icon('');

                $id = $this->id;
                $link = $this->mini_app_short_link;

                return admin_view('admin.article.short_link', compact('id', 'link'));
            });
            $grid->column('hot_news_tag.name', '标签');
            $grid->column('title');
            $grid->column('content')->width('500px')->limit(50, '...');
            $grid->column('is_hot')->using(['否', '是'])->label([
                'danger', 'primary'
            ]);
            $grid->column('is_top')->using(['否', '是'])->label([
                'danger', 'primary'
            ]);

            $grid->disableFilterButton();
            $grid->disableRefreshButton();
            $grid->disableBatchDelete();
            $grid->disableViewButton();
            $grid->disableRowSelector();

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->append('<a style="margin-right:5px" href="' . admin_route('article_comments.index', ['article_id' => $actions->row->id]) . '">查看评论</a>');
                $actions->append('<a style="margin-right:5px" href="' . admin_route('article_comments.create', ['article_id' => $actions->row->id]) . '">添加评论</a>');
            });

            $grid->filter(function (Grid\Filter $filter) use ($map) {
                $filter->panel();
                $filter->expand();
//                $filter->scope('trashed', '回收站')->onlyTrashed();
                $filter->equal('mini_type')->select($map)->width(2);
                $filter->equal('id')->width(2);
                $filter->between('created_at')->datetime()->width(4);
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Article(), function (Show $show) {
            $show->field('id');
            $show->field('publish_id');
            $show->field('type');
            $show->field('title');
            $show->field('desc');
            $show->field('file_type');
            $show->field('file_ids');
            $show->field('thum_img');
            $show->field('content');
            $show->field('is_hot');
            $show->field('is_top');
            $show->field('first_relay_count');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Article(), function (Form $form) {
            $form->display('id');
            $form->select('mini_type')->options(function () {
                return getAuthMiniProgramMap(Admin::user()->id);
            })->required();
            $form->hidden('type')->value('1');
            $publishers = Publisher::all()->pluck('name', 'id');
            $form->select('publish_id')->options($publishers);
            $form->text('title')->required();
            $form->select('tag_id', '标签')
                ->saving(function ($v) {
                    return (int)$v;
                })
                ->options(Tag::where('type', '=', TagConstant::TAG_BY_HOT_NEWS)->pluck('name', 'id')->all());

            $form->radio('file_type')
                ->when(1, function (Form $form) {
                    $form->multipleImage('files', ' ')->sortable()->uniqueName()
                        ->saving(function ($value) {
                            return implode(',', $value);
                        })->customFormat(function ($v) { // 转换为显示的格式
                            return $v;
                        })->limit(9)->saveFullUrl()->help('建议尺寸: 750X560PX');
                })
                ->when(2, function (Form $form) {
                    $form->file('video', ' ')->chunked()->chunkSize(1024 * 5)->maxSize(1024 * 2 * 1000)->autoUpload()->uniqueName()->saveFullUrl();
                    $form->image('thum_img', '视频封面')->uniqueName()->autoUpload()->saveFullUrl();
                })
                ->options([
                    1 => '图片',
                    2 => '视频',
                ])
                ->default(1);
            $form->textarea('content')->rules('required|string', [
                'required' => '内容必填',
            ]);
            $form->radio('is_hot')->options(['否', '是'])->default('0');
            $form->radio('is_top')->options(['否', '是'])->default('0');
            $form->text('first_relay_count')->default(0);
            $form->text('first_fav_count')->default(0);
            $form->display('created_at');
            $form->display('updated_at');

            $form->saving(function (Form $form) {
                $file_type = $form->file_type;
                $thum_img = $form->thum_img;
                $files = $form->files;
                if ($file_type == 2 && !$thum_img) {
                    return $form->response()->error('视频封面必传');
                } elseif ($file_type == 1 && !$files) {
                    return $form->response()->error('素材图片必传');
                }
            });

            $form->deleted(function (Form $form, $result) {
                // 获取待删除行数据，这里获取的是一个二维数组
                $data = $form->model()->toArray();

                // 通过 $result 可以判断数据是否删除成功
                if (!$result) {
                    return $form->response()->error('数据删除失败');
                }

                ArticleComment::where(['article_id' => $data[0]['id']])->delete();

                // 返回删除成功提醒，此处跳转参数无效
                return $form->response()->success('删除成功');
            });

        });
    }

    public function generateShortLink(Request $request)
    {
        $id = $request->input('id');
        if (!$id) return response()->json(['status' => false, 'msg' => 'id不能为空']);

        $info = \App\Models\Article::find($id);
        if (!$info) return response()->json(['status' => false, 'msg' => '信息不存在']);

        if (!$info->mini_type) return response()->json(['status' => false, 'msg' => '请先归属小程序']);

        $ret = app(MiniProgramService::class)->getShortLink(
            $info->mini_type,
            $info->type == 1 ? 'pages/index/newsListContent/index?id=' . $id : 'pages/index/advertiseContent/index?id=' . $id,
            $info->title ?: '',
        );

        if (!$ret['status']) return response()->json(['status' => false, 'msg' => $ret['msg']]);

        $link = $ret['data'] ?? '';
        if (!$link) return response()->json(['status' => false, 'msg' => '生成短链失败']);

        $info->update(['mini_app_short_link' => $link]);
        return response()->json(['status' => true, 'data' => $link, 'msg' => '操作成功']);
    }
}
